﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MINERP.GroupMember.IView;
using MINERP.GroupMember.Presenter;
using MINERP.ComControls;
using Leadtools.Codecs;
using Leadtools;
using Leadtools.WinForms;
using System.IO;
using System.Diagnostics;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.Collections.Specialized;
using MINERP.MODEL.FoundationModel;
using MINERP.COM;
using MINERP.MODEL.GroupMember;
using System.Configuration;

namespace MINERP.GroupMember
{
    public partial class FrmTool : FrmParent, IFrmTool
    {
        private FrmToolPresenter _presenter;
        private PicBrowser browser = new PicBrowser();//用于显示图片
        private List<string> _UserDropDirPath;

        private bool _IsExtens = true;//屏开
        private int _userId;
        public static string stopRemark;//暂停产品原因



        //快捷键
        private int _HTLookTasks = 1, _HTEXTEN = 2;//1为查看任务列表，2-收缩或展开


        public FrmTool()
        {
            InitializeComponent();
            base.InitiAuthority();
            SetLoacation();//将工具栏放在最右边
            try
            {
                chkUseCamera.Checked = Convert.ToBoolean(ConfigurationManager.AppSettings["UseCamero"]);
                DataTransfer.IsUseCamero = chkUseCamera.Checked;
            }
            catch (Exception)
            {
                ModifyConfigurationOP.SetConfig("UseCamero", "False");
                chkUseCamera.Checked = false;
            }

            browser.MouseDown += new MouseEventHandler(browser_MouseDown);
            browser.MouseDoubleClick += new MouseEventHandler(browser_MouseDoubleClick);
            browser.MouseUp += new MouseEventHandler(browser_MouseUp);
            browser.KeyDown += new KeyEventHandler(browser_KeyDown);
            browser.KeyUp += new KeyEventHandler(browser_KeyUp);
        }

        void browser_KeyUp(object sender, KeyEventArgs e)
        {
            isControlDown = false;
        }

        void browser_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control)
                isControlDown = true;
        }

        void browser_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                PicBrowser b = (PicBrowser)sender;
                if (b._list.Count == 0)
                {
                    previousRectangles.Clear();
                    foreach (RasterImageListItem item in b.SelectedItems)
                    {
                        previousRectangles.Add(b.GetItemRectangle(item));
                    }
                }
                else if (isIn == false)
                {
                    previousRectangles.Clear();
                    foreach (RasterImageListItem item in b.SelectedItems)
                    {
                        previousRectangles.Add(b.GetItemRectangle(item));
                    }
                }
            }
        }

        void browser_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            try
            {
                previousRectangles.Clear();
                Cursor = Cursors.WaitCursor;
                Common.OpenPS();
                PicBrowser browser = (PicBrowser)sender;
                if (browser.SelectedItems.Count > 0)
                {
                    Process.Start("PhotoShop.exe", browser.SelectedItems[0].Tag.ToString());
                }
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        List<Rectangle> previousRectangles = new List<Rectangle>();
        DateTime previous = DateTime.Now;
        bool isIn = false;  //鼠标位置是否在缩略图范围之内
        bool isControlDown = false; //Ctrl键是否按下
        //缩略图鼠标按下事件(触发拖曳操作)
        void browser_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                #region 双击操作
                DateTime now = DateTime.Now;
                TimeSpan span = now - previous;
                previous = now;
                if (span.Hours == 0 && span.Minutes == 0 && span.Seconds == 0 && span.Milliseconds < 300)
                {
                    browser_MouseDoubleClick(sender, e);  //执行双击事件
                    return;     //执行了双击事件就不再执行拖曳操作
                }
                #endregion

                PicBrowser browser = (PicBrowser)sender;
                if (browser._list.Count == 0)
                {
                    if (browser.SelectedItems.Count > 0) //表示鼠标正好处于某张照片范围之内
                    {
                        string[] files = new string[1];
                        files[0] = browser.SelectedItems[0].Tag.ToString();
                        DataObject data = new DataObject();
                        data.SetData(DataFormats.FileDrop, files);
                        DoDragDrop(data, DragDropEffects.All);
                        browser_MouseUp(sender, e);   //保存选中的照片Rectangle
                    }
                }
                else
                {
                    isIn = false;
                    int x = e.X;
                    int y = e.Y;
                    foreach (Rectangle r in previousRectangles)
                    {
                        if (x >= r.Left && x <= r.Right && y >= r.Top && y <= r.Bottom)
                        {
                            if (isControlDown == false)
                            {
                                isIn = true;
                                break;
                            }
                        }
                    }
                    if (isIn == true)   //拖曳操作
                    {
                        string[] files = new string[browser._list.Count];
                        for (int i = 0; i < browser._list.Count; i++)
                        {
                            files[i] = browser._list[i].Tag.ToString();
                            browser._list[i].Selected = true;
                        }
                        DataObject data = new DataObject();
                        data.SetData(DataFormats.FileDrop, files);
                        DoDragDrop(data, DragDropEffects.All);
                        browser_MouseUp(sender, e);
                    }
                    else
                    {
                        if (browser.SelectedItems.Count > 0)
                        {
                            string[] files = new string[1];
                            files[0] = browser.SelectedItems[0].Tag.ToString();
                            DataObject data = new DataObject();
                            data.SetData(DataFormats.FileDrop, files);
                            DoDragDrop(data, DragDropEffects.All);
                            browser_MouseUp(sender, e);
                        }
                    }
                }
            }
        }

        void SetLoacation()
        {
            this.Height = (Screen.PrimaryScreen.WorkingArea.Height - 20);
            this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, 0);
        }

        private void btnLookTask_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetLoacation();
            this.Cursor = Cursors.WaitCursor;
            _presenter.OpenTaskListForm();
            this.Cursor = Cursors.Default;
        }

        private void btnOpenPS_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                Common.OpenPS();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region IFrmTool 成员

        public List<string> SelectedPhotoBarCode
        {
            get
            {
                List<string> selectedBarcode = new List<string>();
                foreach (var item in gridView1.GetSelectedRows())
                {
                    selectedBarcode.Add(((PhotoInfo_GM)gridView1.GetRow(item)).PhotoBarCode);
                }
                return selectedBarcode;
            }
        }

        public void ShowHeadInfo(string orderProductId, string productName, string shopName, string ctmName, string prodctSize, string pageNum, string remark)
        {
            lblOrderProductId.Text = "产品编号：" + orderProductId;
            lblProductName.Text = "产品：" + productName;
            lblShopName.Text = "商户：" + shopName;
            lblCtmName.Text = "客户：" + ctmName;
            LblProductSize.Text = "尺寸：" + prodctSize + " 英寸";
            lblPageNum.Text = "P数：" + pageNum;
            txtRequire.Text = remark;
        }

        public void showComposeProudct(List<Tb_Product_Info> listComposeProduct)
        {
            gridControl4.Visible = true;
            memoEdit1.Height = panel2.Height - gridControl4.Height - 3;
            memoEdit1.Location = new Point(gridControl4.Location.X, gridControl4.Location.Y + gridControl4.Height + 5);
            gridControl4.DataSource = listComposeProduct;
        }

        public void HideComposeProduct()
        {
            gridControl4.Visible = false;
            memoEdit1.Height = panel2.Height - 5;
            memoEdit1.Location = new Point(gridControl4.Location.X, gridControl4.Location.Y);
        }


        public List<string> SelectedPicPath
        {
            get
            {
                List<string> list = new List<string>();
                if (gridView2.RowCount < 1)
                {
                    return null;
                }
                foreach (var item in gridView2.GetSelectedRows())
                {
                    list.Add(((MINERP.MODEL.GroupMember.BigPicInfo)gridView2.GetRow(item)).PicName);
                }
                return list;
            }
        }

        public List<string> DropDirPath
        {
            get { return _UserDropDirPath; }
        }

        public void ShopPic(List<string> _picPathList)
        {
            //显示图片列表
            browser.Visible = true;
            this.gridControl1.Visible = false;

            browser.Location = gridControl1.Location;
            browser.Width = gridControl1.Width;
            browser.Height = gridControl1.Height;
            browser.Anchor = gridControl1.Anchor;
            browser.SelectionMode = RasterImageListSelectionMode.Multi;

            browser.Items.Clear();
            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();
            try
            {
                foreach (string picPath in _picPathList)
                {
                    //加载缩略图
                    CodecsThumbnailOptions options = new CodecsThumbnailOptions();
                    options.LoadStamp = true;//加载缩略图
                    options.Resample = true;
                    options.MaintainAspectRatio = true;
                    RasterImage img;
                    try
                    {
                        img = codecs.ReadThumbnail(picPath, options, 1);
                    }
                    catch
                    {
                        options.LoadStamp = false;//如果图片没有缩略图就直接加载原图
                        img = codecs.ReadThumbnail(picPath, options, 1);
                    }
                    FileInfo fi = new FileInfo(picPath);

                    RasterImageListItem Thumb = new RasterImageListItem(img, 1, fi.Name);
                    Thumb.Tag = picPath;
                    browser.Items.Add(Thumb);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("找不到图片，图片是否被移动", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                xtraTabPage1.Controls.Add(browser);
                codecs.Dispose();
                RasterCodecs.Shutdown();
            }
        }

        public void ClearForm()
        {
            //清空界面
            gridControl1.DataSource = null;
            gridControl2.DataSource = null;
            gridControl2.DataSource = null;
            if (_UserDropDirPath != null)
            {
                _UserDropDirPath.Clear();
            }

            memoEdit1.Text = "";
            lblOrderProductId.Text = "产品编号：";
            lblProductName.Text = "产品：";
            lblShopName.Text = "商户：";
            lblCtmName.Text = "客户：";
            LblProductSize.Text = "尺寸：";
            lblPageNum.Text = "Page数：";

            tabImportPic.SelectedTabPageIndex = 0;
            browser.Items.Clear();
            ShowPhotoList(null);
            tabImportPic.Enabled = false;
            labelControl4.Visible = true;
        }

        public void ShowImportPicList(List<MINERP.MODEL.GroupMember.BigPicInfo> _ImportPicList)
        {

            gridControl2.DataSource = _ImportPicList;
            gridControl2.RefreshDataSource();

            if (_ImportPicList.Count < 1)
            {
                toolStripButton8.Enabled = false;
                if (!checkBox1.Checked)
                {
                    toolStripButton5.Enabled = false;
                }
                else
                {
                    toolStripButton5.Enabled = true;
                }
            }
            else
            {
                toolStripButton8.Enabled = true;
                toolStripButton5.Enabled = true;
            }
            barStaticItem2.Caption = _ImportPicList.Count.ToString();

        }
        public void ShowRemark(string strRemark)
        {
            this.memoEdit1.Text = strRemark;
        }

        public void BindCtm(List<string> ctmList)
        {
            //
        }
        public int userid
        {
            get
            {
                return _userId;//test
            }
        }

        public void ShowPhotoList(DataTable dtSource)
        {
            gridControl1.Visible = true;
            browser.Visible = false;
            this.gridControl1.DataSource = dtSource;
        }

        public void HidenDesignPanel()
        {
            toolStripButton7.Visible = true;
            xtraTabPage3.PageVisible = false;
            barButtonItemSetWorkFolder.VisibleWhenVertical = false;
            buttonCreateFolder.Visible = false;
            CommonSettings();
        }

        public void ShowDesingPanel()
        {
            toolStripButton7.Visible = false;

            xtraTabPage3.PageVisible = true;
            CommonSettings();
        }

        void CommonSettings()
        {
            tabImportPic.Enabled = true;
            labelControl4.Visible = false;
            barStaticItem2.Caption = gridView1.RowCount.ToString();
            barStaticItem4.Caption = "操作员：" + base.userName;
            groupBox1.Enabled = true;
        }

        #endregion

        protected override void WndProc(ref Message msg)
        {
            const int WM_HOTKEY = 0x0312; // 热键消息

            if (msg.Msg != WM_HOTKEY)
            {
                if (msg.Msg == WM_NCLBUTTONDBLCLK)
                {
                    if (frmToolDisplayMode == false)
                    {
                        this.Height = 30;
                        frmToolDisplayMode = true;  //工具条只显示头部
                    }
                    else
                    {
                        this.Height = frmToolPreviousHeight;
                        frmToolDisplayMode = false; //工具条高度正常
                    }
                    return;
                }
                base.WndProc(ref msg);
            }
            else
            {
                if ((int)msg.WParam == _HTLookTasks)
                {
                    if (!DataTransfer.taskFrmIsOpen)
                    {
                        SetLoacation();
                        this.Cursor = Cursors.WaitCursor;
                        DataTransfer.taskFrmIsOpen = true;
                        _presenter.OpenTaskListForm();
                        this.Cursor = Cursors.Default;

                    }
                }
                else if ((int)msg.WParam == _HTEXTEN)
                {
                    if (_IsExtens)//如果是展开的
                    {
                        //就收缩起来                       
                        this.Height = 30;
                        frmToolDisplayMode = true;  //工具条只显示头部


                        _IsExtens = false;
                    }
                    else
                    {
                        //就展开
                        this.Height = frmToolPreviousHeight;
                        frmToolDisplayMode = false; //工具条高度正常
                        _IsExtens = true;
                    }
                }
            }
        }

        private void FrmTool_Load(object sender, EventArgs e)
        {
            _userId = base.userId;
            DataTransfer.UserName = base.userName;
            DataTransfer.GroupName = base.GroupName;
            _presenter = new FrmToolPresenter(this);
            #region 注册快捷键

            WinHotKey hy = new WinHotKey();
            hy.SetHotKey(this.Handle, false, false, true, false, Keys.Q, _HTLookTasks);//查看任务列表
            hy.SetHotKey(this.Handle, false, false, true, false, Keys.W, _HTEXTEN);//收缩列表
            #endregion

            frmToolPreviousHeight = this.Height;
            this.TopMost = checkEditTopDisplay.Checked = Properties.Settings.Default.IsTopDisplay;
            
            barStaticItem4.Caption = base.userName;
            _presenter.OpenTaskListForm();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

            //列表与图片进行切换
            this.Cursor = Cursors.WaitCursor;
            toolStripButton1.Enabled = false;
            _presenter.ChangeView();
            toolStripButton1.Enabled = true;
            this.Cursor = Cursors.Default;
        }

        #region 只显示工具条的头部
        bool frmToolDisplayMode = false;    //工具条的显示模式 false正常 true只显示头部
        int frmToolPreviousHeight = 0;      //记录工具条正常模式下的高度
        const int WM_NCLBUTTONDBLCLK = 0xA3;

        #endregion

        private void gridControl2_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.All;
            }
            else

                e.Effect = DragDropEffects.None;
        }

        private void gridControl2_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = e.Data.GetData(DataFormats.FileDrop) as string[];
            if (_UserDropDirPath == null)
            {
                _UserDropDirPath = new List<string>();
            }
            foreach (string filePath in files)
            {
                _UserDropDirPath.Add(filePath);
            }

            _presenter.DoDragPicFromOutSide();

            _UserDropDirPath.Clear();
            toolStripButton5.Enabled = true;
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.Description = "选择设计好的文件夹";
            if (!string.IsNullOrEmpty(Properties.Settings.Default.WorkFolder))
            {
                folderBrowserDialog1.SelectedPath = Properties.Settings.Default.WorkFolder;
            }
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                this.Cursor = Cursors.WaitCursor;
                if (_UserDropDirPath == null)
                {
                    _UserDropDirPath = new List<string>();
                }
                _UserDropDirPath.Add(folderBrowserDialog1.SelectedPath);
                _presenter.DoDragPicFromOutSide();
                this.Cursor = Cursors.Default;
            }

        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            //加载原图
            _presenter.LoadOriginalPic();
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            //完成（非设计类工作）
            this.Cursor = Cursors.WaitCursor;
            try
            {
                _presenter.CompleteWork(txtRequire.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            //导入新设计后的图片
            this.Cursor = Cursors.WaitCursor;
            _presenter.ImportNewDesignedPicAndOver();
            this.Cursor = Cursors.Default;
        }

        private void tabImportPic_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (tabImportPic.SelectedTabPage.Name == "xtraTabPage2")
            {
                _presenter.SelectRemark();
            }
            else if (tabImportPic.SelectedTabPage.Name == "xtraTabPage3")
            {
                if (!DataTransfer.SelectTaskInfo.IsDeisgnTech)
                {
                    tabImportPic.SelectedTabPageIndex = 0;
                }
                else
                {
                    if (gridControl2.MainView.RowCount < 1)
                    {
                        if (!checkBox1.Checked)
                        {
                            toolStripButton5.Enabled = false;
                        }
                        else
                        {
                            toolStripButton5.Enabled = true;
                        }

                    }
                }
            }
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            //从dataSource中册除选定的图片
            _presenter.DeletePic();
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == openFileDialog1.ShowDialog())
            {
                this.Cursor = Cursors.WaitCursor;
                if (_UserDropDirPath == null)
                {
                    _UserDropDirPath = new List<string>();
                }
                _UserDropDirPath.Clear();
                foreach (var item in openFileDialog1.FileNames)
                {
                    _UserDropDirPath.Add(item);
                }
                _presenter.DoDragPicFromOutSide();
                this.Cursor = Cursors.Default;
            }
        }

        GridHitInfo downHitInfo = null;
        private void gridView1_MouseDown(object sender, MouseEventArgs e)
        {
            GridView view = sender as GridView;
            downHitInfo = null;

            GridHitInfo hitInfo = view.CalcHitInfo(new Point(e.X, e.Y));

            if (Control.ModifierKeys != Keys.None) return;
            if (e.Button == MouseButtons.Left && hitInfo.InRow && hitInfo.HitTest != GridHitTest.RowIndicator)
                downHitInfo = hitInfo;
        }

        private void gridView1_MouseMove(object sender, MouseEventArgs e)
        {
            GridView view = sender as GridView;
            if (e.Button == MouseButtons.Left && downHitInfo != null)
            {
                Size dragSize = SystemInformation.DragSize;
                Rectangle dragRect = new Rectangle(new Point(downHitInfo.HitPoint.X - dragSize.Width / 2,
                    downHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);

                if (!dragRect.Contains(new Point(e.X, e.Y)))//当他移出这个区域后就开始拖操作
                {
                    DataObject data = new DataObject();
                    data.SetData(DataFormats.FileDrop, GetDragData(view));
                    view.GridControl.DoDragDrop(data, DragDropEffects.Copy);
                    ChangeIsEdit();
                    gridControl1.RefreshDataSource();
                    downHitInfo = null;
                }
            }
        }
        #region helper methods

        private void ChangeIsEdit()
        {
            foreach (var rowIndex in gridView1.GetSelectedRows())
            {
                ((PhotoInfo_GM)gridView1.GetRow(rowIndex)).IsEdit = true;
            }
        }

        private string[] GetDragData(GridView view)
        {
            int[] selection = view.GetSelectedRows();
            if (selection == null) return null;
            int count = selection.Length;
            string[] result = new string[count];
            for (int i = 0; i < count; i++)
            {
                result[i] = ((PhotoInfo_GM)view.GetRow(selection[i])).PicPath;
            }
            return result;
        }

        #endregion

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //复制
            StringCollection files = new StringCollection();
            foreach (var item in gridView1.GetSelectedRows())
            {
                files.Add(((PhotoInfo_GM)gridView1.GetRow(item)).PicPath);
            }

            Clipboard.SetFileDropList(files);
        }

        private void 还原ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (DialogResult.Yes == MessageBox.Show("确定要还原选择的图片吗？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                _presenter.RecoverSelectedPic();
            }
        }

        private void BtnHistroyTask_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)//查看已完成的
        {
            SetLoacation();
            _presenter.LookHistory();

        }

        private void FrmTool_FormClosed(object sender, FormClosedEventArgs e)
        {
            Logoff.ShowMainFrm();
        }

        private void gridView1_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                if (((PhotoInfo_GM)gridView1.GetRow(e.RowHandle)).IsRebackPhoto)
                {
                    e.Appearance.BackColor = Color.Red;
                }
                else if (!((PhotoInfo_GM)gridView1.GetRow(e.RowHandle)).SizeIsRight)
                {
                    e.Appearance.BackColor = Color.Red;
                }
                else if (((PhotoInfo_GM)gridView1.GetRow(e.RowHandle)).IsEdit)
                {
                    e.Appearance.BackColor = Color.GreenYellow;
                }
            }
        }

        private void gridView1_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            gridControl1.RefreshDataSource();
        }

        private void gridView1_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.Name == "IsEdit" && (bool)e.CellValue)
            {
                gridView1.SetRowCellValue(e.RowHandle, gridView1.Columns["IsEdit"], false);
            }
        }

        private void FrmTool_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("确认退出？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)
            {
                //取消热键注册
                WinHotKey.UnregisterHotKey(this.Handle, _HTEXTEN);
                WinHotKey.UnregisterHotKey(this.Handle, _HTLookTasks);
            }
            else
            {
                e.Cancel = true;
            }

        }

        #region IFrmTool 成员


        public void ShowHeaderInfo(TaskInfo taskInfo)
        {
            lblOrderProductId.Text = "产品编号：" + taskInfo.OrderProductId.ToString();

            lblProductName.Text = "产品：" + taskInfo.ProductName;
            lblShopName.Text = "商户：" + taskInfo.ShopName;
            lblCtmName.Text = "客户:" + taskInfo.CtmName;
            LblProductSize.Text = "尺寸:" + taskInfo.ProductSize + " 英寸";
            lblPageNum.Text = "P数:" + taskInfo.PageNum;
            txtRequire.Text = taskInfo.ProductRemark;
            labelAreas.Text = "面积:"+taskInfo.Areas.ToString("0.0000")+"平方米";
        }

        public void ShowPhotos(List<PhotoInfo_GM> Plist)
        {
            gridControl1.Visible = true;
            browser.Visible = false;
            this.gridControl1.DataSource = Plist;
        }

        #endregion

        private void barCheckItem1_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (barCheckItem1.Checked)
            {
                barCheckItem1.Caption = "自动开启";
                barCheckItem1.Appearance.Font = new Font("Tahoma", 14);
            }
            else
            {
                barCheckItem1.Caption = "自动关闭";
                barCheckItem1.Appearance.Font = new Font("Tahoma", 9);
            }

            DataTransfer.IsAutoGetTask = barCheckItem1.Checked;
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            _presenter.ShowConntecionFrm();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            _presenter.ReBackTask(txtRequire.Text);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                toolStripButton5.Enabled = true;
                DataTransfer.IsOriPicOver = true;
            }
            else
            {
                DataTransfer.IsOriPicOver = false;
                if (gridView2.RowCount < 1)
                {
                    toolStripButton5.Enabled = false;
                }
            }
        }

        private void chkUseCamera_CheckedChanged(object sender, EventArgs e)
        {
            ModifyConfigurationOP.SetConfig("UseCamero", chkUseCamera.Checked ? "True" : "False");
            DataTransfer.IsUseCamero = chkUseCamera.Checked;
        }

        #region IFrmTool 成员


        public string OrderRemark
        {
            get { return txtRequire.Text.Trim(); }
        }

        #endregion

        private void btnOpenFolder_Click(object sender, EventArgs e)
        {
            //打开当前任务的目录
            if (DataTransfer.SelectTaskInfo != null)
            {
                MINERP.BLL.Common.FileBLL.OpenFoler(DataTransfer.SelectTaskInfo.OrderPath);
            }

        }

        private void buttonCreateFolder_Click(object sender, EventArgs e)
        {
            string rootFolder = Properties.Settings.Default.WorkFolder;
            if (string.IsNullOrEmpty(rootFolder))
            {
                MessageBox.Show("请先设定工作目录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string DateFolder = rootFolder + "\\" + DateTime.Now.Date.ToString("yyyy-MM-dd");
            if (!Directory.Exists(DateFolder))
            {
                Directory.CreateDirectory(DateFolder);
            }
            string ShopFolder = DateFolder + "\\" + DataTransfer.SelectTaskInfo.ShopName;
            if (!Directory.Exists(ShopFolder))
            {
                Directory.CreateDirectory(ShopFolder);
            }

            string CtmFolder = ShopFolder + "\\" + DataTransfer.SelectTaskInfo.CtmName;
            if (!Directory.Exists(CtmFolder))
            {
                Directory.CreateDirectory(CtmFolder);
            }
            List<TaskInfo> taskInfoList = _presenter.GetProductList(DataTransfer.SelectTaskInfo.CtmName);
            foreach (var taskInfo in taskInfoList)
            {
                string productFolder = CtmFolder + "\\" + taskInfo.OrderProductId+"_"+taskInfo.OrderProductName;
                if (!Directory.Exists(productFolder))
                {
                    Directory.CreateDirectory(productFolder);
                }
                else
                {
                    if (MessageBox.Show(productFolder + "文件夹已存在是否重建", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        Directory.Delete(productFolder,true);
                        Directory.CreateDirectory(productFolder);
                    }
                }
                foreach (var item in taskInfo.PhotoList)
                {
                    File.Copy(item.PicPath, productFolder + item.PicPath.Substring(item.PicPath.LastIndexOf("\\")));
                }
            }
            MessageBox.Show("客人产品文件夹创建成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        //设定工作目录
        private void barButtonItemSetWorkFolder_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();

            if (string.IsNullOrEmpty(Properties.Settings.Default.WorkFolder))
            {
                folder.RootFolder = Environment.SpecialFolder.Desktop;
            }
            else
            {
                folder.SelectedPath = Properties.Settings.Default.WorkFolder;

            }

            if (folder.ShowDialog() == DialogResult.OK)
            {
                Properties.Settings.Default.WorkFolder = folder.SelectedPath;
                Properties.Settings.Default.Save();
                MessageBox.Show("工作目录设定成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }


        }

        private void gridView2_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if ("数量".Equals(e.Column.Caption))
            {
                MINERP.MODEL.GroupMember.BigPicInfo picinfo = (MINERP.MODEL.GroupMember.BigPicInfo)gridView2.GetRow(e.RowHandle);
                picinfo.NUM = Convert.ToInt32(e.Value);
            }
        }

        private void barbtnEPbyPhotoSpec_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmEPByPhotoSpec frm = new FrmEPByPhotoSpec(this.userName);
            frm.ShowDialog();
        }

        private void gridView2_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {

            GridView gv = sender as GridView;
            BigPicInfo bigpic = gv.GetRow(e.RowHandle) as BigPicInfo;
            if (bigpic.IsMatchSize == false)
            {
                e.Appearance.BackColor = Color.Red;
            }

        }

        private void barbtnPanse_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("您确定要暂停生产该产品吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                try
                {
                    int orderProductId =  DataTransfer.SelectTaskInfo.OrderProductId;
                    FrmStopRemark frm = new FrmStopRemark();
                    frm.ShowDialog();
                    _presenter.PauseOrderProduct(orderProductId, 0, stopRemark, userId);
               
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    stopRemark = "";//清空备注
                }
            }
        }

        private void checkEditTopDisplay_CheckedChanged(object sender, EventArgs e)
        {
            bool isTopDisplay = checkEditTopDisplay.Checked;
            Properties.Settings.Default.IsTopDisplay = isTopDisplay;
            this.TopMost = isTopDisplay;
            Properties.Settings.Default.Save();
        }
    }
}
